package yzx.firstletter.appList.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import yzx.firstletter.BaseFragment;
import yzx.firstletter.R;
import yzx.firstletter.appList.LetterSelectItemView;
import yzx.firstletter.util.GenericCallback;


public class LetterSelectFragment extends BaseFragment {


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_letter_select, container, false);
        view.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
        initEvent(view);
        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    public static final String TAG_ALL = "全部";
    public static final String TAG_OTHER = "*";
    private static final String[] TAGS = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",TAG_OTHER,TAG_ALL};
    private List<LetterSelectItemView> itemViewList = new ArrayList<>(TAGS.length);
    private void initEvent(View view){
        View.OnClickListener l = new View.OnClickListener(){
            public void onClick(View v) {
                String tag = (String) v.getTag();
                if(onClickCallback != null)
                    onClickCallback.callback(tag);
            }
        };
        int selectedBgColor = ResourcesCompat.getColor(getResources(), R.color.letter_selected_item_bg_selected, null);
        for (String tag : TAGS) {
            LetterSelectItemView item = (LetterSelectItemView) view.findViewWithTag(tag);
            item.setSelectedBgColor(selectedBgColor);
            item.setOnClickListener(l);
            itemViewList.add(item);
        }
    }



    private String currentTag;


    /**  */
    public String getCurrentTag() {
        return currentTag;
    }
    /** 回调 26字母 数字 符号 */
    public GenericCallback<String> onClickCallback;
    /** 设置选中样式 */
    public void setSelectedState(final String tag){
        if(tag.equals(currentTag)) return ;
        currentTag = tag;
        Runnable run = new Runnable(){
            public void run() {
                for (LetterSelectItemView view : itemViewList)
                    view.setSelectedState(view.getTag().equals(tag));
            }
        };
        if(isResumed()) run.run();
        else addOnResumeCallbackOnce(run);
    }

}
